package com.odobenus.zk;

import java.util.ArrayList;
import java.util.List;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 基于 ZooKeeper 的客戶端发现实现
 */
public class ZooKeeperServiceDiscovery {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperServiceDiscovery.class);
	private static List<String> serviceList = new ArrayList<String>();
	private final ZkClient zkClient;

	public ZooKeeperServiceDiscovery(String zkAddress) {
		zkClient = new ZkClient(zkAddress, Constant.ZK_SESSION_TIMEOUT, Constant.ZK_CONNECTION_TIMEOUT);
		String path = Constant.ZK_REGISTRY_PATH;
		try {
			List<String> appList = zkClient.getChildren(path);
			appList.stream().forEach(app->{
				LOGGER.info("read from zk;"+app);
				String[] app_address=app.split(Constant.ZK_SPLIT_EXPRESSION);
				serviceList.add(app_address[1].replaceAll("\\\\", "/"));
			});
			registerWatch(path);
			LOGGER.info("serviceList="+serviceList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 注册监听，感知服务上下线
	public void registerWatch(String path) throws Exception {
		// 对父节点添加监听子节点变化。
		zkClient.subscribeChildChanges(path, new IZkChildListener() {
			@Override
			public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
				LOGGER.info("handleChildChange after read from zk currentChilds="+currentChilds);
				serviceList=new ArrayList<String>();
				currentChilds.stream().forEach(app->{
					String[] app_address=app.split(Constant.ZK_SPLIT_EXPRESSION);
					serviceList.add(app_address[1].replaceAll("\\\\", "/"));
				});
			}
		});
	}

	public List<String> discover() {
		System.out.println("node List = "+serviceList);
		return serviceList;
	}
}